package com.huilian.iotbox.admin.service.impl;

import com.huilian.iotbox.admin.service.FileService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.properties.FileProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.UUID;


@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileProperties fileProperties;

    @Override
    public String getFileUrl() {
        return fileProperties.getSaveImgPath();
    }

    @Override
    public ServerResponse upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //扩展名
        String fileExtensionName = fileName.substring(fileName.lastIndexOf('.') + 1);

        //限定只能上传PNG,GIF,JPG,JPEG
        ArrayList<String> list = new ArrayList<>();
        list.add("JPG");
        list.add("PNG");
        list.add("GIF");
        list.add("JPEG");

        boolean flag = false;

        for (String str : list) {
            if (StringUtils.equalsIgnoreCase(fileExtensionName, str)) {
                flag = true;
                break;
            }
        }

        if (!flag) {
            return ServerResponse.createByErrorMessage("上传的图片类型不正确,请上传gif,jpg,jpeg,png格式的图片");
        }

        //UUID做文件名，现在使用是前台传入的文件名，所以要保证前台传入的文件名的维一性
        String uploadFileName = UUID.randomUUID().toString() + "." + fileExtensionName;

        log.info("开始上传文件,上传文件的文件名:{},上传的路径:{},新文件名{}", fileName, this.getFileUrl(), fileName);

        File fileDir = new File(this.getFileUrl());

        //如果路径不存在就创建
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            boolean mkdirs = fileDir.mkdirs();
        }
        File targetFile = new File(this.getFileUrl(), fileName);

        try {
            file.transferTo(targetFile);
            //文件已经上传成功了！
        } catch (IOException e) {
            log.error("上传文件异常", e);

            return ServerResponse.createByError();
        }
        return ServerResponse.createBySuccess(targetFile.getName());
    }


    @Override
    public ServerResponse delete(String fileName) {
        if (fileName == null) {
            return ServerResponse.createByErrorMessage("传入的文件名为空");
        }
        File file = new File(this.getFileUrl(), fileName);
        boolean result = file.delete();
        if (result) {
            log.info("{}图片删除成功！", fileName);
            return ServerResponse.createBySuccessMessage("图片删除成功");
        } else {
            log.error("{}图片删除失败！", fileName);
            return ServerResponse.createByErrorMessage("图片删除失败");
        }
    }


    @Override
    public void download(String fileName, HttpServletResponse response) throws Exception {
        try (InputStream inputStream = new FileInputStream(new File(this.getFileUrl(), fileName));
             OutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }
}
